<template>
	<view>
		<view v-if="!graceFullLoading">
			
			<view class="fixedit" :style="{top:top}">
				<scroll-view scroll-x id="grace-tab-title" class="grace-tab-title grace-center" scroll-with-animation :scroll-left="scrollLeft">
					<view class="cu-item" :class="index==TabCur?'cur':'text-blue'" v-for="(item,index) in navData" 
						:key="index" @tap="tabSelect" :data-id="index" :data-en="item.key" :data-type="item.type">
						{{item.value}}
					</view>
				</scroll-view>
			</view>
			
			<view style="height:30px;"></view>
			
			<view class="grace-news-list" style="width:94%; padding:15px 3%;">
<!-- 			<navigator>
					<view class="grace-news-list-items">
						<view class="grace-news-list-title">
							<view class="grace-news-list-title-main">阿里员工揭秘：很多程序员离职，在小公司当领导，只动嘴不动手！</view>
							<view class="grace-news-list-info">
								<view>
									<text class="grace-iconfont"></text> 新闻资讯
									<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> 5天前
								</view>
							</view>
						</view>
						<image src="../../../static/logo.png" class="grace-news-list-img grace-list-imgs-r" mode="widthFix"></image>
					</view>
				</navigator>
				<navigator>
					<view class="grace-news-list-items">
						<view class="grace-news-list-title">
							<view class="grace-news-list-title-main">阿里巴巴是中国知名的互联网公司，每个人或多或少的都从淘宝上购买的物品</view>
							<view class="grace-news-list-info">
								<view>
									<text class="grace-iconfont"></text> 新闻资讯
									<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> 5天前
								</view>
							</view>
						</view>
						<image src="../../../static/logo.png" class="grace-news-list-img grace-list-imgs-r" mode="widthFix"></image>
						<view class="grace-news-tips grace-news-tips-r">新闻</view>
					</view>
				</navigator>
				 
				<navigator>
					<view class="grace-news-list-img-news">
						<view class="grace-news-list-title-main">一个项目经理不搞砸几个项目，是无法成长为一名合格的项目经理的</view>
						<view class="grace-news-list-imgs">
							<image src="../../../static/logo.png" mode="widthFix"></image>
							<image src="../../../static/logo.png" mode="widthFix"></image>
							<image src="../../../static/logo.png" mode="widthFix"></image>
						</view>
					</view>
					<view class="grace-news-list-info">
						<view>
							<text class="grace-iconfont"></text> 新闻资讯
							<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> 5天前
						</view>
					</view>
				</navigator>
				<navigator>
					<view class="grace-news-list-img-news">
						<view class="grace-news-list-title-main">一个项目经理不搞砸几个项目，是无法成长为一名合格的项目经理的</view>
						<view class="grace-news-list-img-big"><image src="../../../static/imgbanner.png" mode="widthFix"></image></view>
					</view>
					<view class="grace-news-list-info">
						<view>
							<text class="grace-iconfont"></text> 新闻资讯
							<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> 5天前
						</view>
					</view>
				</navigator> -->
				<view v-for="(item, index) in dataList" :key="index" @click="goDetail(index)">
					<label v-if="item.covers.length<2">
					<view class="grace-news-list-items">
						<view class="grace-news-list-title">
							<view class="grace-news-list-title-main">{{item.title}}</view>
							<view class="grace-news-list-info">
								<view>
									{{item.cn}}
									<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> {{item.createtime}}
								</view>
							</view>
						</view>
						<block v-for="(image,k) in item.covers" :key="k">
							<image :src="serverUrl+image" class="grace-news-list-img grace-list-imgs-r" mode="widthFix"></image>
						</block>	
					</view>	
					</label>
					<label v-if="item.covers.length>1">
					<view class="grace-news-list-img-news">
						<view class="grace-news-list-title-main">{{item.title}}</view>
						<view class="grace-news-list-imgs">
						<block v-for="(image,k) in item.covers" :key="k">
							<image :src="serverUrl+image" mode="widthFix"></image>
						</block>	
						</view>
					</view>
					<view class="grace-news-list-info">
						<view>
							{{item.cn}}
							<text class="grace-iconfont icon-time2" style="margin-left:20px;"></text> {{item.createtime}}
						</view>
					</view>		
					</label>	
				</view>
			</view>
			
		</view>
		<graceFullLoading :graceFullLoading="graceFullLoading" logoUrl="/static/logo.png"></graceFullLoading>
		<view style="text-align:center;" v-show="dataShow">数据为空</view>				
	
	</view>
</template>

<script>
	import graceFullLoading from "../../../graceUI/components/graceFullLoading.vue";
	import {
		mapState,
		mapMutations
	} from 'vuex';
	var _self;
	var en = '';
	var type = 'recommendData';
	var page = 1;
	export default {
		computed: {
		    ...mapState(['userInfo','databaseInfo','propertyInfo'])
		},		
		data() {
			return {
				serverUrl: this.serverUrl,
				top: 0,
				TabCur: 0,
				scrollLeft: 0,
				navData:[],
				dataList:[],
				dataShow: false
				
			};
		},
		onLoad:function(){
			//第一次启动引导页
			this.loadExecution();
			//登录缓存
			const appKey = uni.getStorageSync('appKey');
			if(appKey!=""){
				this.findUser(appKey);
			}
			//存储搜索历史
			// this.saveOldKeyword();
			//导航分类列表
			this.getDbList();
			this.getDataList();
			_self = this;
			//关闭loading
			setTimeout(function(){
				_self.graceFullLoading = false;
			}, 1000);
			
		},
		components:{
			graceFullLoading
		},
		//下拉刷新
		onPullDownRefresh: function() {
			// 重置分页及数据
			page = 1;
			this.dataList = [];
			this.getDataList();		
		},
		// 加载更多
		onReachBottom: function() {
			this.getDataList();
		},		
		methods:{
			...mapMutations(['login','setDatabaseInfo','setPropertyInfo']),
			loadExecution: function(){
				/**
				 * 获取本地存储中launchFlag的值
				 * 若存在，说明不是首次启动，直接进入首页；
				 * 若不存在，说明是首次启动，进入引导页；
				 */
				try {
				    const value = uni.getStorageSync('launchFlag');
				    if (value) {
				        if (value == true) {
				            uni.switchTab({
				                url: '/pages/tab-bar/home/home'
				            });
				        } else {
				            uni.redirectTo({
				                url: '/pages/general/guide/guide'
				            });
				        }
				    } else {
				        uni.setStorage({
				            key: 'launchFlag',
				            data: true,
				            success: function() {
								//console.log('存储launchFlag');
							}
				        });
				        uni.redirectTo({
				                url: '/pages/general/guide/guide'
				        });
				    }
				} catch(e) { 
					uni.setStorage({ 
						key: 'launchFlag', 
						data: true, 
						success: function () {
							//console.log('error时存储launchFlag');
						} 
					}); 
					uni.redirectTo({ url: '/pages/general/guide/guide' }); 
				}
			},
			findUser(appKey) {
				uni.request({
					url: this.serverUrl + 'user-api/findUser',
					data: {
						appKey: appKey,
					},
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					method: "POST",
					success: (r) => {
						//console.log(r);
						if (r.data.code == '000000') {
							this.login(r.data.data); 
						} else {
							uni.showToast({
								title: r.data.message
							});
						}
					}
				});
			},	
			saveOldKeyword() {
				var OldKeys = "";
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var temp = JSON.parse(res.data);
						for(var i=0;i<temp.length;i++){
							OldKeys+=temp[i]+";";
						}
						uni.request({
							url: this.serverUrl + 'user-api/updateMemberModel',
							data: {
								username:this.userInfo.username,
								historySearchText: OldKeys,
							},
							header: {
								"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
							},
							method: "POST",
							success: (r) => {
								//console.log(r);
								if (r.data.code == '000000') {
									//console.log(r.data.data); 
								} else {
									uni.showToast({
										title: r.data.message
									});
								}
							}
						});	
					}
				});
			},
			goDetail(index) {
				let obj = {
					id: this.dataList[index].id,
					type: this.dataList[index].type,
					title: this.dataList[index].title,
					author: this.dataList[index].author,
					create_time_str: this.dataList[index].createtime,
					cover: this.dataList[index].covers
				}
				if(this.dataList[index].type=='xwzx') {
					uni.navigateTo({
						url: "/pages/news/detail/detail?id=" + obj.id
					})
				}else if(this.dataList[index].type=='jsbk') {
					uni.navigateTo({
						url: "/pages/search/baike-detail/baike-detail?obj=" + encodeURIComponent(JSON.stringify(obj))
					})
				}else {
					uni.navigateTo({
						url: "/pages/search/detail/detail?obj=" + encodeURIComponent(JSON.stringify(obj))
					})
				}
				
			},								
			getDbList() {
				var data = {
					// recommend: "1",
					pageNumber: 1,
					pageSize: 100
				};
				uni.request({
					url: this.serverUrl + 'search-api/getDatabase',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					data: data,
					method: "POST",
					success: (r) => {
						// console.log(r);
						if(r.data.code=='000000') {
							// console.log(r.data.data);
							let databaseInfoTemp = [];
							for (var i = 0; i < r.data.data.length; i++) {
								var tmpObj = {
									key: r.data.data[i].nameEn,
									value: r.data.data[i].nameCn,
									type: 'recommendData'
								};
								databaseInfoTemp.push(tmpObj);
							}
							//console.log(databaseInfoTemp);
							this.navData = [{
										key:'',
										value:'推荐',
										type:'recommendData'
									},{
										key:'',
										value:'最新',
										type:'updateData'
									}];
							this.navData = this.navData.concat(databaseInfoTemp);
							//赋值全局变量
							this.setDatabaseInfo(databaseInfoTemp);
						}else {
							uni.showToast({
								title: r.data.message
							});
						}
					},
					fail: (data, code) => {
						console.log('fail' + JSON.stringify(data));
					}
				})
			},	
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				en = e.currentTarget.dataset.en;
				type = e.currentTarget.dataset.type;
				page = 1;
				this.dataList = [];
				this.getDataList();
			},
			getDataList() {
				var hideload = 0;
				uni.showLoading();
				// 历史搜索
				let OldKeys = "";
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var temp = JSON.parse(res.data);
						for(var i=0;i<temp.length;i++){
							OldKeys+=temp[i]+";";
						}
					}
				});
				console.log(OldKeys);
				var data = {
					databaseEn: en,
					type: type,
					pageNum: page,
					pageSize: 10,
					username:this.userInfo.username,
					historySearchText: OldKeys
				};
				uni.request({
					url: this.serverUrl + 'search-api/getListByRecommend',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					data: data,
					method: "POST",
					success: (r) => {
						// console.log(r);
						if(r.data.code=='000000') {
							//console.log(r.data.data);
							// 假设已经到底， 实际根据api接口返回值判断
							if (r.data.data.data.length < 1) {
								hideload = 1;
								uni.hideLoading();
								if (this.dataList.length < 1) {
									this.dataShow = true;
								}else{
									uni.showToast({
										title: "已经加载全部",
										icon: "none",
										duration: 1500
									});
								}
								return;
							}else{
								this.dataShow = false;
							}													
							for (var i = 0; i < r.data.data.data.length; i++) {
								//作者
								let authorTmp = '';
								if(null!=r.data.data.data[i].author && r.data.data.data[i].author!='') {
									for (var m = 0; m < r.data.data.data[i].author.length; m++) {
										authorTmp += r.data.data.data[i].author[m] + " ";
									}
								}								
								var tmpObj = {
									id: r.data.data.data[i].id[0],
									title: r.data.data.data[i].title[0],
									author: authorTmp,
									type: r.data.data.data[i].type[0],
									cn: r.data.data.data[i].database_cn[0],
									covers: r.data.data.data[i].cover==null?[]:r.data.data.data[i].cover[0].split(";"),
									createtime: r.data.data.data[i].create_time_str[0]
								};
								this.dataList = this.dataList.concat(tmpObj);
							}
							page++;
						}else {
							uni.showToast({
								title: r.data.message
							});
						}
					},
					fail: (data, code) => {
						console.log('fail' + JSON.stringify(data));
					},
					complete: r => {
						if (hideload == 0) {
							uni.hideLoading();
						}
						uni.stopPullDownRefresh();
					}
				})
			}					
		}
	}
</script>

<style>
.cur {
	font-size: 32rpx;
	font-weight: bold;
	color: #000;
	border-bottom:6rpx solid #417dc9 !important;
	padding: 0.1rpx;
}
.grace-tab-title {
	background-color: #F8F8FF;
	padding-left: 15upx;
}

.grace-tab-title view:last-child {
	padding-right: 20upx;
}
.grace-tab-title view {
	font-size: 32rpx;
	padding: 0 2px;
	margin: 0 8px;
	line-height: 32px;
}
.grace-tab-title .text-blue {
	border-bottom:6rpx solid #F8F8FF !important;
}
.grace-news-list-title {
	margin: 10upx 0;
}
.grace-news-list-title-main {
	font-size: 32rpx;
}

/* 分段器头部 fixed 定位 */
.fixedit {
	width: 100%;
	position: fixed;
	z-index: 99;
	left: 0;
	top: 0;
}

.grace-news-list-imgs {
	max-height: 180upx;
	overflow: hidden;
}

.grace-news-list-imgs image {
	border-radius: 5upx;
}
.grace-news-list-img-big image {
	border-radius: 5upx;
}	
.grace-news-list-img-big {
	max-height: 300upx;
	overflow: hidden;
}
.grace-list-imgs-r {
	border-radius: 5upx;
	max-height: 180upx;
	overflow: hidden;
}
</style>
